package pattern.singleton;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;

public class SingletonTest {

    public static void main(String[] args)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException, ClassNotFoundException {
        // 反射攻击
//        Singleton7 singleton = Singleton7.getInstance();
//        Constructor<Singleton7> singletonCons = Singleton7.class.getDeclaredConstructor();
//        singletonCons.setAccessible(true);
//        Singleton7 singletonCopy = singletonCons.newInstance();
//        System.out.println(singleton);
//        System.out.println(singletonCopy);

        // 序列化和反序列化
        Singleton7 singleton = Singleton7.getInstance();
        System.out.println(singleton);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton.txt"));
        oos.writeObject(singleton);
        oos.flush();
        oos.close();

        FileInputStream fis = new FileInputStream("singleton.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Singleton7 singletonCopy = (Singleton7) ois.readObject();
        ois.close();
        fis.close();

        System.out.println(singletonCopy);
        System.out.println(singleton == singletonCopy);

    }
}
